#include "friendimageprovider.h"
#include "sdk/public/steam/steam_api.h"

FriendImageProvider::FriendImageProvider() : QQuickImageProvider(QQuickImageProvider::Pixmap) {

}

QPixmap FriendImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) {
    qDebug() << "Friend requestPixmap called with " << id;
    CSteamID steamID;
    steamID.SetFromUint64(id.toLongLong());
    int imageHandle = SteamFriends()->GetSmallFriendAvatar(steamID);
    if (imageHandle == 0) {
        qDebug() << "Error getting avatar for id " << id;
        return QPixmap();
    }
    unsigned int width, height;
    bool result = SteamUtils()->GetImageSize(imageHandle, &width, &height);
    if (!result) {
        qDebug() << "Failed to get image size";
        return QPixmap();
    }
    size->setHeight(height);
    size->setWidth(width);
    int sizeInBytes = height * width * 4;
    unsigned char *pAvatar = new unsigned char[sizeInBytes];
    result = SteamUtils()->GetImageRGBA(imageHandle, pAvatar, sizeInBytes);
    if (!result) {
        qDebug() << "Failed to get image content";
        delete[] pAvatar;
        return QPixmap();
    }
    QImage ret(pAvatar, width, height, QImage::Format_RGB32);
    return QPixmap::fromImage(ret);
}
